package com.ruike.alisurface.ui.payPage;

import android.content.DialogInterface;
import android.os.SystemClock;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ruike.alisurface.Constant;
import com.ruike.alisurface.MyApplication;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.Serials.Ttys3Utils;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.CarGoodsBeans;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.ui.adapter.PayCarListAdapter;
import com.ruike.alisurface.ui.dialog.CustomDialog;
import com.ruike.alisurface.ui.mainPage.MainActivity;
import com.ruike.alisurface.utils.BackMainUtils;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

import static com.ruike.alisurface.Constant.isOpenCardOperation;
import static com.ruike.alisurface.utils.ShareKey.Type_toGoshopzl;

/**
 * Author: voodoo
 * CreateDate: 2020-03-31 031 下午 09:20
 * Description: 选择支付方式
 */
public class SelectPayTypeActivity extends BaseAty {

    @BindView(R.id.selectPay_countDown_tv)
    TextView selectPayCountDownTv;
    @BindView(R.id.selectPay_goback_imgv)
    ImageView selectPayGobackImgv;

    @BindView(R.id.selectPay_goodsList_recv)
    RecyclerView selectPayGoodsListRecv;
    List<CarGoodsBeans> paycarlist;
    @BindView(R.id.pay_type_weface)
    ImageView payTypeWeface;
    @BindView(R.id.pay_type_wechat)
    ImageView payTypeWechat;
    @BindView(R.id.pay_type_wecard)
    ImageView payTypeWecard;
    @BindView(R.id.img_rk_adv)
    ImageView imgRkAdv;

    @BindView(R.id.pay_type_yhmj)
    TextView payTypeYhmj;
    @BindView(R.id.pay_type_yhljm)
    TextView payTypeYhljm;
    @BindView(R.id.pay_type_mjyh)
    RelativeLayout payTypeMjyh;
    @BindView(R.id.pay_type_zklv)
    TextView payTypeZklv;
    @BindView(R.id.pay_type_zkyh)
    RelativeLayout payTypeZkyh;
    @BindView(R.id.layout_yhhd)
    LinearLayout layout_yhhd;

    static Timer timer;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_select_pay;
    }

    @Override
    protected void onResume() {
        super.onResume();
        startCountdownTimer(120, selectPayCountDownTv, MainActivity.class);
        boolean isOpenAlipayPay = ShareUtils.getInstance().getBoolean(ShareKey.IS_OPEN_ALIPAY_PAY, true); // 启用 支付宝刷脸支付
        if (isOpenAlipayPay) {
            payTypeWeface.setVisibility(View.VISIBLE);
        } else {
            payTypeWeface.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initViews() {
        MchApiHttp.getActivityType(this);
        payTypeWecard.setVisibility(isOpenCardOperation ? View.VISIBLE : View.GONE);
        Constant.showShop = true;
        L.i("选择出货方式页==" + this.getClass().getName());
        initTitleBar(false);
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        if (requestUrl.endsWith("GetActivity")) {
            try {
                JSONObject jsonObject = new JSONObject(requestJsonStr);

                JSONObject data = jsonObject.getJSONObject("data");

                if (jsonObject.optInt("code") == 0) {
                    L.i("获取活动==");
                    String now_activity_id = data.optString("now_activity_id");
                    String activity_json = data.optString("activity_json");
                    L.i("acty_id=acty_config==", now_activity_id, activity_json);
                    L.i("acty_id=acty_config===", ShareUtils.getInstance().getString(ShareKey.ACTIVITY_ID, "0"));

                    setDataHuoDong(now_activity_id, activity_json);

                }

            } catch (JSONException e) {
                L.i("获取活动=errr=" + e.getMessage());
            }

        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        super.onError(requestUrl, errorMsg);
        if (requestUrl.endsWith("GetActivity")) {
        }
    }

    @Override
    protected void initData() {

        try {
            paycarlist = MyApplication.finalDbUtils.findAll(CarGoodsBeans.class);
        } catch (Exception e) {
            L.i("Exception==", e.getLocalizedMessage());
        }

        SystemClock.sleep(100);
        if (paycarlist != null) {
            selectPayGoodsListRecv.setLayoutManager(new GridLayoutManager(this, paycarlist.size()));
            selectPayGoodsListRecv.setHasFixedSize(true);
            selectPayGoodsListRecv.setAdapter(new PayCarListAdapter(this, paycarlist));
        }
    }

    //    PopupDialog popupDialog;
    int paytype; // 1刷脸  2扫码支付  3卡支付

    @OnClick({R.id.selectPay_goback_imgv, R.id.pay_type_weface,
            R.id.pay_type_wechat, R.id.pay_type_wecard})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.selectPay_goback_imgv:
                BackMainUtils.setActivity(this);
                finish();
                break;
            case R.id.pay_type_weface: // 刷脸支付
                IntentActivity(1);
                break;
            case R.id.pay_type_wechat: // 扫码支付
                IntentActivity(2);
                break;
            case R.id.pay_type_wecard: // 刷卡支付
                IntentActivity(3);
                break;
        }
    }

    /**
     * 支付类型的判断 及发送能否通信的指令即返回值操作
     * 跳转到不同的页面
     *
     * @param type
     */
    private void IntentActivity(int type) {
        if (paycarlist == null) {
            showLongTip("商品数据异常，请重新选择商品", 5000);
            return;
        }
        paytype = type;
        // 通过发送灯光指令判断是否能够通讯
        Ttys3Utils.getInstance().LEDSetting(10, "1", "2", "1", 15, 15);
        if (timer == null) {
            timer = new Timer();
        }
        L.i("通信计时1====开始");
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        L.i("通信计时2====结束");
                        alt();
                    }
                });
            }
        }, 3000);

    }

    @Override
    protected void onStop() {
        super.onStop();
        Constant.showShop = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
        }
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    CustomDialog dialog;

    /**
     * 通讯异常提示框
     */
    private void alt() {
        try {
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
            dialog = new CustomDialog.Builder(this)
                    .setTitle("温馨提示").setMessage("底层通信出现异常，暂时停止购买，请稍后重试!!!")
                    .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (dialog != null) {
                                dialog.dismiss();
                            }
                        }
                    })
                    .setTouchOutsideCloseDialog(false).create();
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String Tag = getClass().getCanonicalName();

    @Override
    public void doEventBusResult(MsgEventBus event) {
        if (event.getType().equals(Type_toGoshopzl)) {
            if (timer != null) {
                timer.cancel();
                timer.purge();
                timer=null;
            }
            L.i(Tag + "--购买前的通信指令---" + event.getMessage() + " =跳转类型=" + paytype);
            if (paytype == 1) {
                startActivity(PayAlFaceActivity.class, null);
            } else if (paytype == 2) {
                startActivity(PayForQRCodeActivity.class, null);
            } else if (paytype == 3) {
                startActivity(PayCardActivity.class, null);
            }
            finish();
        }
    }

    /**
     * 活动显示数据判断
     *
     * @param now_activity_id
     * @param activity_json
     * @throws JSONException
     */
    public void setDataHuoDong(String now_activity_id, String activity_json) throws JSONException {
        if (TextUtils.isEmpty(now_activity_id)) {

            return;
        }
        if (now_activity_id.equals("1")) {  // 转盘
            layout_yhhd.setVisibility(View.GONE);

            return;
        }
        if (TextUtils.isEmpty(activity_json)) {

            return;
        }

        JSONObject Js = new JSONObject(activity_json);
        if (now_activity_id.equals("2")) {  //满减

            layout_yhhd.setVisibility(View.VISIBLE);
            payTypeMjyh.setVisibility(View.VISIBLE);
            payTypeZkyh.setVisibility(View.GONE);
            String full = Js.optString("full", "");
            String reduce = Js.optString("reduce", "");
            payTypeYhmj.setText(full + "");
            payTypeYhljm.setText(reduce + "");

            return;
        }
        if (now_activity_id.equals("3")) {  //折扣

            layout_yhhd.setVisibility(View.VISIBLE);
            payTypeZkyh.setVisibility(View.VISIBLE);
            payTypeMjyh.setVisibility(View.GONE);
            String off_rate = Js.optString("off_rate", "0");
            int zhek = Double.valueOf(off_rate).intValue();
            payTypeZklv.setText(zhek + "");

            return;
        }
    }
}
